import process from "node:process";
import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import { visualizer } from "rollup-plugin-visualizer";
import vue from "@vitejs/plugin-vue";

let tauri = !!process.env.TAURI_PLATFORM;
let target;
if (!tauri) {
  target = "modules";
} else if (process.env.TAURI_PLATFORM == "windows") {
  target = "chrome105";
} else {
  target = "safari13";
}

// https://vitejs.dev/config/
export default defineConfig({
  clearScreen: false,
  server: {
    strictPort: true,
  },
  envPrefix: [
    "VITE_",
    "TAURI_PLATFORM",
    "TAURI_ARCH",
    "TAURI_FAMILY",
    "TAURI_PLATFORM_VERSION",
    "TAURI_PLATFORM_TYPE",
    "TAURI_DEBUG"
  ],
  define: {
    __UNDER_TAURI__: tauri ? "true" : "false"
  },
  plugins: [
    vue({
      include: [/\.vue$/, /\.md$/],
      template: {
        compilerOptions: {
          isCustomElement: (tag) => tag.includes("md-")
        }
      }
    }),
    visualizer({
      gzipSize: true,
      brotliSize: true,
      emitFile: false,
      filename: "visualizer.html"
    })
  ],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url))
    }
  },
  build: {
    target,
    chunkSizeWarningLimit: 1024,
    rollupOptions: {
      output: {
        manualChunks: (id) => {
          if (id.includes("node_modules/vue-echarts")) {
            return "map";
          } else if (id.includes("node_modules/@fontsource") || id.includes("node_modules/material-symbols")) {
            return "fonts";
          } else if (id.includes("node_modules/@vue")) {
            return "vendor";
          } else if (id.includes("node_modules/echarts") || id.includes("node_modules/zrender")) {
            return "map";
          } else if (id.includes("assets/map")) {
            return "asset-map";
          } else if (id.includes("node_modules")) {
            return "vendor";
          }
        }
      }
    }
  }
});
